<template>
  <div ref="divRef" style="height: 600px;width: 50vw"/>
</template>


<script setup lang="ts">
import {AiEditor} from "aieditor";
import "aieditor/dist/style.css"
import {onMounted, onUnmounted, ref} from "vue";

const divRef = ref();
let aiEditor: AiEditor | null = null;
const content = ref('AiEditor 是一个面向 AI 的开源富文本编辑器。 ');
onMounted(() => {
  aiEditor = new AiEditor({
    element: divRef.value as Element,
    // draggable:false,
    placeholder: "点击输入内容...",
    content: content.value,
    image: {
      uploadUrl: "http://localhost:8181/file/upload",
      uploadFormName: "file",
      uploader: (file, uploadUrl, headers, formName) => {
        console.log("uploader--uploader")
        const formData = new FormData();
        formData.append(formName, file);
        return new Promise((resolve, reject) => {
          fetch(uploadUrl, {
            method: "post",
            headers: {'Accept': 'application/json', ...headers},
            body: formData,
          }).then((resp) => resp.json())
              .then(json => {
                resolve(json);
              }).catch((error) => {
            reject(error);
          })
        });
      },
      uploaderEvent: {
        onUploadBefore: (file, uploadUrl, headers) => {
          //监听图片上传之前，此方法可以不用回任何内容，但若返回 false，则终止上传
        },
        onSuccess: (file, response) => {
          //监听图片上传成功
          //注意：
          // 1、如果此方法返回 false，则图片不会被插入到编辑器
          // 2、可以在这里返回一个新的 json 给编辑器
          console.log("onSuccess",response)
          return{
            "errorCode": 0,
            "data": {
              "src": response.msg,
              "alt": "图片 alt"
            }
          }
        },
        onFailed: (file, response) => {
          //监听图片上传失败，或者返回的 json 信息不正确
        },
        onError: (file, error) => {
          //监听图片上传错误，比如网络超时等
        },
      },
    },
  })
})
http://localhost:8181/file/upload
onUnmounted(() => {
  aiEditor && aiEditor.destroy();
})

</script>


<style scoped>

</style>